// 📦 引入工具库
const _ = require("lodash");
const path = require("path");
const fs = require("fs");

// 📦 ESM 支持模块加载
const esm = require("esm");
const requireModule = esm(module);

// 📦 项目依赖模块
const { readAllValues } = requireModule(
  "../awakened-potential/helpers/readAllValues.js"
);
const checkAccuracy = requireModule("./utils/checkAccuracy.js");

// ✅ 读取历史开奖数据（模拟全部）
const allValues = readAllValues("m");

// ✅ 号码池（01 ~ 49）
const allNumbers = Array.from({ length: 49 }, (_, i) =>
  (i + 1).toString().padStart(2, "0")
);
// ✅ 是否使用窗口
const useWindow = true;
// ✅ 窗口大小
const windowSize = 5;
// 预测结果
const predictResults = [];

// ✅ 初始化马尔科夫转移矩阵（转移次数）
const transitionMatrix = {}; // 结构: { fromNumber: { toNumber: count } }
allNumbers.forEach((from) => {
  transitionMatrix[from] = {};
  allNumbers.forEach((to) => {
    transitionMatrix[from][to] = 0;
  });
});

allValues.forEach((item, index) => {
  const temp = useWindow
    ? allValues.slice(Math.max(0, index - windowSize), index)
    : allValues.slice(0, index);

  // ✅ 没有足够参考历史不预测
  if (temp.length === 0 || index === 0) return;

  // ✅ 上一期号码
  const lastNumber = allValues[index - 1].number;
  const transitionRow = transitionMatrix[lastNumber];

  // ✅ 预测
  const prediction = Object.entries(transitionRow)
    .sort((a, b) => b[1] - a[1])
    .map(([num]) => num)
    .slice(0, 32);

//   console.log(_.uniq(prediction).length);

  // ✅ 记录预测结果
  predictResults.push(checkAccuracy(prediction, item.number));

  // ✅ 现在才更新转移矩阵！不要偷看答案
  const prev = lastNumber;
  const curr = item.number;
  if (transitionMatrix[prev] && transitionMatrix[prev][curr] != null) {
    transitionMatrix[prev][curr]++;
  }
});

// 计算准确率
const total = predictResults.length;
const correct = predictResults.filter((x) => x === 1).length;
const accuracy = total > 0 ? ((correct / total) * 100).toFixed(2) : 0;

// 计算最大连续错误次数
let maxWrongStreak = 0;
let currentStreak = 0;
predictResults.forEach((res) => {
  if (res === 0) {
    currentStreak++;
    if (currentStreak > maxWrongStreak) {
      maxWrongStreak = currentStreak;
    }
  } else {
    currentStreak = 0;
  }
});

// 输出统计结果
console.log(`预测总数: ${total}`);
console.log(`命中次数: ${correct}`);
console.log(`准确率: ${accuracy}%`);
console.log(`最大连续错误次数: ${maxWrongStreak}`);
